<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>省份费率维护 - 运费计算器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .slide-in { animation: slideIn 0.4s ease-out forwards; }
        @keyframes slideIn {
            from { transform: translateY(10px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        .input-error { border-color: #ef4444 !important; }
        .error-text { color: #ef4444; font-size: 0.75rem; margin-top: 0.25rem; }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-sans">
    <!-- 顶部导航栏 -->
    <header class="bg-blue-600 text-white shadow-md">
        <div class="container mx-auto px-4 py-5">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center">
                <div>
                    <h1 class="text-2xl md:text-3xl font-bold flex items-center">
                        <i class="fa fa-calculator mr-3"></i>运费计算器管理平台
                    </h1>
                    <p class="mt-1 text-blue-100">动态费率配置系统</p>
                </div>
                <div class="mt-3 md:mt-0">
                    <span class="text-sm bg-blue-700 px-3 py-1 rounded-full">
                        <i class="fa fa-clock-o mr-1"></i>
                        <span id="current-date"></span>
                    </span>
                </div>
            </div>
        </div>
    </header>

    <!-- 功能导航 -->
    <nav class="bg-white border-b border-gray-200">
        <div class="container mx-auto px-4">
            <div class="flex overflow-x-auto py-3 space-x-6 md:space-x-8 whitespace-nowrap">
                <a href="/" class="text-gray-600 hover:text-blue-600 transition-colors flex items-center">
                    <i class="fa fa-calculator mr-2"></i>基础计算
                </a>
                <a href="/manage" class="text-blue-600 font-medium border-b-2 border-blue-600 pb-2 flex items-center">
                    <i class="fa fa-sliders mr-2"></i>费率维护
                </a>
                <a href="/excel" class="text-gray-600 hover:text-blue-600 transition-colors flex items-center">
                    <i class="fa fa-file-excel-o mr-2"></i>批量测算
                </a>
            </div>
        </div>
    </nav>

    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-8">
        <div class="max-w-4xl mx-auto">
            <!-- 页面标题 -->
            <div class="mb-8 slide-in">
                <h2 class="text-2xl font-bold text-gray-800 flex items-center">
                    <i class="fa fa-map-marker text-blue-500 mr-3"></i>省份费率配置
                </h2>
                <p class="mt-2 text-gray-600">配置不同省份的运费计算规则，支持多重量段和多种计费方式</p>
            </div>

            <!-- 重要提示：边界规则说明 -->
            <div class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-6 rounded-r slide-in" style="animation-delay: 0.1s">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fa fa-info-circle text-blue-500 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-blue-700">
                            <strong>重量段边界规则：</strong>
                            0-1表示0≤重量≤1（1kg属于此段），1-2表示1&lt;重量≤2（1.1kg属于此段），
                            无上限段请将最大重量留空（如2-表示2&lt;重量）
                        </p>
                    </div>
                </div>
            </div>

            <!-- 省份基本信息表单 -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6 slide-in" style="animation-delay: 0.2s">
                <h3 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b border-gray-200">
                    <i class="fa fa-building text-gray-500 mr-2"></i>省份基本信息
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="provinceName" class="block text-sm font-medium text-gray-700 mb-1">
                            省份名称 <span class="text-red-500">*</span>
                        </label>
                        <input 
                            type="text" 
                            id="provinceName" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-150 ease-in-out"
                            placeholder="例如：上海、北京"
                            onblur="validateProvinceName()"
                        >
                        <div id="provinceNameError" class="error-text hidden"></div>
                        <p class="mt-1 text-xs text-gray-500">省份名称不可重复，用于区分不同地区的费率</p>
                    </div>
                    
                    <div>
                        <label for="calcType" class="block text-sm font-medium text-gray-700 mb-1">
                            计费方式 <span class="text-red-500">*</span>
                        </label>
                        <select 
                            id="calcType" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-150 ease-in-out appearance-none bg-white"
                            onchange="validateCalcType()"
                        >
                            <option value="">-- 请选择计费方式 --</option>
                            <option value="weight_step">重量阶梯计费（按不同重量段阶梯收费）</option>
                            <option value="fixed_add">固定续重计费（首重+续重模式）</option>
                            <option value="piece">按件计费（与重量无关，按件数收费）</option>
                        </select>
                        <div id="calcTypeError" class="error-text hidden"></div>
                        <p class="mt-1 text-xs text-gray-500">选择后将应用于该省份的所有重量段</p>
                    </div>
                </div>
            </div>

            <!-- 费率段配置表格 -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6 slide-in" style="animation-delay: 0.3s">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fa fa-tasks text-gray-500 mr-2"></i>费率段配置 <span class="text-red-500">*</span>
                    </h3>
                    <button 
                        id="addRateBtn" 
                        class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition duration-150 ease-in-out"
                    >
                        <i class="fa fa-plus mr-2"></i>添加费率段
                    </button>
                </div>

                <!-- 费率段表格 -->
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    重量段（kg）
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    费率（元）<span class="text-red-500">*</span>
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    基础费（元）
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    排序号<span class="text-red-500">*</span>
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    操作
                                </th>
                            </tr>
                        </thead>
                        <tbody id="rateTableBody" class="bg-white divide-y divide-gray-200">
                            <!-- 初始费率段行 -->
                            <tr class="hover:bg-gray-50 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center space-x-2">
                                        <input 
                                            type="number" 
                                            step="0.1" 
                                            min="0" 
                                            class="weight-min w-20 px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                                            placeholder="最小"
                                            onblur="validateWeightMin(this)"
                                        >
                                        <span class="text-gray-500">-</span>
                                        <input 
                                            type="number" 
                                            step="0.1" 
                                            min="0" 
                                            class="weight-max w-20 px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                                            placeholder="最大"
                                            onblur="validateWeightMax(this)"
                                        >
                                        <span class="text-xs text-gray-500">(留空=无上限)</span>
                                    </div>
                                    <div class="weight-min-error error-text hidden"></div>
                                    <div class="weight-max-error error-text hidden"></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input 
                                        type="number" 
                                        step="0.01" 
                                        min="0" 
                                        class="rate w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                                        placeholder="0.00"
                                        onblur="validateRate(this)"
                                    >
                                    <div class="rate-error error-text hidden"></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input 
                                        type="number" 
                                        step="0.01" 
                                        min="0" 
                                        value="0.00" 
                                        class="base-fee w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                                    >
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input 
                                        type="number" 
                                        min="0" 
                                        value="0" 
                                        class="sort-num w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                                        placeholder="0"
                                        onblur="validateSortNum(this)"
                                    >
                                    <div class="sort-num-error error-text hidden"></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button class="delete-rate-btn text-red-600 hover:text-red-900 transition-colors" disabled>
                                        <i class="fa fa-trash-o mr-1"></i>删除
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4 text-xs text-gray-500">
                    <i class="fa fa-lightbulb-o mr-1 text-yellow-500"></i>
                    提示：至少需要配置1个费率段，排序号用于确定匹配优先级（从小到大）
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex flex-col sm:flex-row justify-center gap-4 slide-in" style="animation-delay: 0.4s">
                <button 
                    id="resetBtn" 
                    class="inline-flex items-center px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition duration-150 ease-in-out"
                >
                    <i class="fa fa-refresh mr-2"></i>重置表单
                </button>
                <button 
                    id="submitBtn" 
                    class="inline-flex items-center px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition duration-150 ease-in-out"
                >
                    <i class="fa fa-save mr-2"></i>保存配置
                </button>
            </div>
        </div>
    </main>

    <!-- 状态提示框 -->
    <div id="toast" class="fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50">
        <i id="toastIcon" class="mr-3 text-xl"></i>
        <span id="toastMessage"></span>
    </div>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white mt-16">
        <div class="container mx-auto px-4 py-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-sm opacity-75">© 2024 运费计算器管理系统</p>
                    <p class="text-xs opacity-50 mt-1">支持动态费率配置与批量测算</p>
                </div>
                <div class="flex space-x-6">
                    <a href="#" class="text-sm opacity-75 hover:opacity-100 transition-opacity">使用帮助</a>
                    <a href="#" class="text-sm opacity-75 hover:opacity-100 transition-opacity">联系我们</a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // 初始化日期显示
        document.getElementById('current-date').textContent = new Date().toLocaleDateString();
        
        // 全局变量
        let rateRowCount = 1;
        const rateTableBody = document.getElementById('rateTableBody');
        
        // 添加费率段行
        document.getElementById('addRateBtn').addEventListener('click', () => {
            rateRowCount++;
            const newRow = document.createElement('tr');
            newRow.className = 'hover:bg-gray-50 transition-colors';
            newRow.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center space-x-2">
                        <input 
                            type="number" 
                            step="0.1" 
                            min="0" 
                            class="weight-min w-20 px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="最小"
                            onblur="validateWeightMin(this)"
                        >
                        <span class="text-gray-500">-</span>
                        <input 
                            type="number" 
                            step="0.1" 
                            min="0" 
                            class="weight-max w-20 px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="最大"
                            onblur="validateWeightMax(this)"
                        >
                        <span class="text-xs text-gray-500">(留空=无上限)</span>
                    </div>
                    <div class="weight-min-error error-text hidden"></div>
                    <div class="weight-max-error error-text hidden"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <input 
                        type="number" 
                        step="0.01" 
                        min="0" 
                        class="rate w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                        placeholder="0.00"
                        onblur="validateRate(this)"
                    >
                    <div class="rate-error error-text hidden"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <input 
                        type="number" 
                        step="0.01" 
                        min="0" 
                        value="0.00" 
                        class="base-fee w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    >
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <input 
                        type="number" 
                        min="0" 
                        value="${rateRowCount - 1}" 
                        class="sort-num w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                        placeholder="${rateRowCount - 1}"
                        onblur="validateSortNum(this)"
                    >
                    <div class="sort-num-error error-text hidden"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button class="delete-rate-btn text-red-600 hover:text-red-900 transition-colors">
                        <i class="fa fa-trash-o mr-1"></i>删除
                    </button>
                </td>
            `;
            
            // 添加到表格并绑定删除事件
            rateTableBody.appendChild(newRow);
            bindDeleteEvent(newRow.querySelector('.delete-rate-btn'));
            
            // 启用初始行的删除按钮
            const firstDeleteBtn = rateTableBody.querySelector('.rate-row:first-child .delete-rate-btn');
            if (rateRowCount > 1) {
                firstDeleteBtn.disabled = false;
            }
        });
        
        // 绑定删除事件
        function bindDeleteEvent(button) {
            button.addEventListener('click', () => {
                const row = button.closest('tr');
                row.classList.add('opacity-0');
                row.style.transition = 'opacity 0.3s ease';
                
                setTimeout(() => {
                    row.remove();
                    rateRowCount--;
                    
                    // 禁用初始行的删除按钮（如果只剩一行）
                    const rows = rateTableBody.querySelectorAll('tr');
                    if (rows.length === 1) {
                        rows[0].querySelector('.delete-rate-btn').disabled = true;
                    }
                    
                    // 重新验证排序号是否重复
                    validateAllSortNums();
                }, 300);
            });
        }
        
        // 重置表单
        document.getElementById('resetBtn').addEventListener('click', () => {
            // 重置省份信息
            document.getElementById('provinceName').value = '';
            document.getElementById('calcType').value = '';
            clearError('provinceName');
            clearError('calcType');
            
            // 清空所有费率段，只保留初始行
            const rows = rateTableBody.querySelectorAll('tr');
            rows.forEach((row, index) => {
                if (index > 0) row.remove();
            });
            
            // 重置初始行数据
            const firstRow = rows[0];
            firstRow.querySelector('.weight-min').value = '';
            firstRow.querySelector('.weight-max').value = '';
            firstRow.querySelector('.rate').value = '';
            firstRow.querySelector('.base-fee').value = '0.00';
            firstRow.querySelector('.sort-num').value = '0';
            firstRow.querySelector('.delete-rate-btn').disabled = true;
            
            // 清除所有错误提示
            firstRow.querySelectorAll('.error-text').forEach(el => {
                el.classList.add('hidden');
            });
            firstRow.querySelectorAll('input').forEach(input => {
                input.classList.remove('input-error');
            });
            
            rateRowCount = 1;
            
            // 显示提示
            showToast('info', '表单已重置');
        });
        
        // 提交表单
        document.getElementById('submitBtn').addEventListener('click', async () => {
            // 先进行全表单验证
            if (!validateForm()) {
                showToast('error', '表单存在错误，请检查并修正后再提交');
                return;
            }
            
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.innerHTML;
            
            // 禁用按钮防止重复提交
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>保存中...';
            
            try {
                // 收集并验证省份信息
                const provinceName = document.getElementById('provinceName').value.trim();
                const calcType = document.getElementById('calcType').value;
                
                // 收集并验证费率段信息
                const rateRows = rateTableBody.querySelectorAll('tr');
                const rates = [];
                const sortNums = new Set();
                
                for (let i = 0; i < rateRows.length; i++) {
                    const row = rateRows[i];
                    const weightMin = parseFloat(row.querySelector('.weight-min').value);
                    const weightMaxInput = row.querySelector('.weight-max').value;
                    const weightMax = weightMaxInput ? parseFloat(weightMaxInput) : null;
                    const rate = parseFloat(row.querySelector('.rate').value);
                    const baseFee = parseFloat(row.querySelector('.base-fee').value) || 0;
                    const sortNum = parseInt(row.querySelector('.sort-num').value);
                    
                    // 添加到数组
                    rates.push({
                        weightMin,
                        weightMax,
                        rate,
                        baseFee,
                        sortNum
                    });
                    
                    sortNums.add(sortNum);
                }
                
                // 发送请求到后端
                const response = await fetch('/api/provinces/with-rates', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: provinceName,
                        calc_type: calcType,
                        rates: rates
                    })
                });
                
                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '保存失败，请重试');
                }
                
                // 保存成功
                showToast('success', `省份"${provinceName}"的费率配置已保存成功！`);
                
                // 重置表单
                setTimeout(() => {
                    document.getElementById('resetBtn').click();
                }, 1500);
                
            } catch (error) {
                // 显示错误信息
                showToast('error', error.message);
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });
        
        // 表单验证函数
        function validateForm() {
            let isValid = true;
            
            // 验证省份名称
            if (!validateProvinceName()) isValid = false;
            
            // 验证计费方式
            if (!validateCalcType()) isValid = false;
            
            // 验证所有费率段
            const rateRows = rateTableBody.querySelectorAll('tr');
            rateRows.forEach(row => {
                if (!validateWeightMin(row.querySelector('.weight-min'))) isValid = false;
                if (!validateWeightMax(row.querySelector('.weight-max'))) isValid = false;
                if (!validateRate(row.querySelector('.rate'))) isValid = false;
                if (!validateSortNum(row.querySelector('.sort-num'))) isValid = false;
            });
            
            // 验证排序号是否重复
            if (!validateAllSortNums()) isValid = false;
            
            return isValid;
        }
        
        // 验证省份名称
        function validateProvinceName() {
            const input = document.getElementById('provinceName');
            const errorEl = document.getElementById('provinceNameError');
            const value = input.value.trim();
            
            if (!value) {
                showError(input, errorEl, '省份名称不能为空');
                return false;
            }
            
            clearError('provinceName');
            return true;
        }
        
        // 验证计费方式
        function validateCalcType() {
            const select = document.getElementById('calcType');
            const errorEl = document.getElementById('calcTypeError');
            const value = select.value;
            
            if (!value) {
                showError(select, errorEl, '请选择计费方式');
                return false;
            }
            
            clearError('calcType');
            return true;
        }
        
        // 验证最小重量
        function validateWeightMin(input) {
            const errorEl = input.parentElement.nextElementSibling; // 获取同级的错误元素
            const value = input.value.trim();
            
            if (!value) {
                showError(input, errorEl, '最小重量不能为空');
                return false;
            }
            
            const num = parseFloat(value);
            if (isNaN(num) || num < 0) {
                showError(input, errorEl, '最小重量必须是非负数');
                return false;
            }
            
            clearInputError(input, errorEl);
            return true;
        }
        
        // 验证最大重量
        function validateWeightMax(input) {
            const errorEl = input.parentElement.nextElementSibling.nextElementSibling;
            const value = input.value.trim();
            const weightMinInput = input.parentElement.querySelector('.weight-min');
            const weightMinValue = weightMinInput.value.trim();
            
            // 最大重量可以为空（表示无上限）
            if (!value) {
                clearInputError(input, errorEl);
                return true;
            }
            
            // 如果填写了最大重量，需要验证
            const num = parseFloat(value);
            if (isNaN(num)) {
                showError(input, errorEl, '最大重量必须是有效的数字');
                return false;
            }
            
            // 如果最小重量已填写，验证最大重量是否大于最小重量
            if (weightMinValue) {
                const weightMin = parseFloat(weightMinValue);
                if (num <= weightMin) {
                    showError(input, errorEl, '最大重量必须大于最小重量');
                    return false;
                }
            }
            
            clearInputError(input, errorEl);
            return true;
        }
        
        // 验证费率
        function validateRate(input) {
            const errorEl = input.nextElementSibling;
            const value = input.value.trim();
            
            if (!value) {
                showError(input, errorEl, '费率不能为空');
                return false;
            }
            
            const num = parseFloat(value);
            if (isNaN(num) || num < 0) {
                showError(input, errorEl, '费率必须是非负数');
                return false;
            }
            
            clearInputError(input, errorEl);
            return true;
        }
        
        // 验证排序号
        function validateSortNum(input) {
            const errorEl = input.nextElementSibling;
            const value = input.value.trim();
            
            if (!value) {
                showError(input, errorEl, '排序号不能为空');
                return false;
            }
            
            const num = parseInt(value);
            if (isNaN(num) || num < 0) {
                showError(input, errorEl, '排序号必须是非负整数');
                return false;
            }
            
            clearInputError(input, errorEl);
            return true;
        }
        
        // 验证所有排序号是否重复
        function validateAllSortNums() {
            const sortInputs = rateTableBody.querySelectorAll('.sort-num');
            const sortNums = new Set();
            let hasDuplicate = false;
            
            sortInputs.forEach(input => {
                const value = input.value.trim();
                if (!value) return; // 已经有其他验证处理空值
                
                const num = parseInt(value);
                if (!isNaN(num)) {
                    if (sortNums.has(num)) {
                        // 找到重复的排序号
                        const errorEl = input.nextElementSibling;
                        showError(input, errorEl, `排序号${num}重复`);
                        hasDuplicate = true;
                    } else {
                        sortNums.add(num);
                        // 清除之前可能的重复错误
                        if (input.classList.contains('input-error') && 
                            errorEl.textContent.includes('重复')) {
                            clearInputError(input, errorEl);
                        }
                    }
                }
            });
            
            return !hasDuplicate;
        }
        
        // 显示错误提示
        function showError(input, errorEl, message) {
            input.classList.add('input-error');
            errorEl.textContent = message;
            errorEl.classList.remove('hidden');
        }
        
        // 清除单个输入框的错误
        function clearInputError(input, errorEl) {
            input.classList.remove('input-error');
            errorEl.textContent = '';
            errorEl.classList.add('hidden');
        }
        
        // 清除指定字段的错误
        function clearError(fieldId) {
            const input = document.getElementById(fieldId);
            const errorEl = document.getElementById(`${fieldId}Error`);
            if (input && errorEl) {
                input.classList.remove('input-error');
                errorEl.textContent = '';
                errorEl.classList.add('hidden');
            }
        }
        
        // 显示提示消息
        function showToast(type, message) {
            const toast = document.getElementById('toast');
            const toastIcon = document.getElementById('toastIcon');
            const toastMessage = document.getElementById('toastMessage');
            
            // 设置提示类型
            if (type === 'success') {
                toast.className = 'fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg bg-green-50 text-green-800 transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50';
                toastIcon.className = 'fa fa-check-circle text-green-500 mr-3 text-xl';
            } else if (type === 'error') {
                toast.className = 'fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg bg-red-50 text-red-800 transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50';
                toastIcon.className = 'fa fa-exclamation-circle text-red-500 mr-3 text-xl';
            } else {
                toast.className = 'fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg bg-blue-50 text-blue-800 transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50';
                toastIcon.className = 'fa fa-info-circle text-blue-500 mr-3 text-xl';
            }
            
            // 设置消息内容
            toastMessage.textContent = message;
            
            // 3秒后隐藏
            setTimeout(() => {
                toast.className = 'fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
            }, 3000);
        }
        
        // 初始化：绑定初始行的删除事件
        document.addEventListener('DOMContentLoaded', () => {
            const firstDeleteBtn = rateTableBody.querySelector('.delete-rate-btn');
            bindDeleteEvent(firstDeleteBtn);
        });
    </script>
</body>
</html>
